package weibo;

import user.UserSession;
import utils.JsonOut;
import utils.MysqlUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "LikeWeiboServlet")
public class LikeWeiboServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();

        String email = UserSession.getUserSessionEmail(session);

        PrintWriter out = response.getWriter();
        if (email == null || email.isEmpty()){
            out.println(JsonOut.error(220, "not_login"));
            return;
        }

        String blogId = request.getParameter("blog_id");
        if (blogId == null || blogId.isEmpty()){
            out.println(JsonOut.error(201, "no_blog_id"));
            return;
        }

        if (!(new MysqlUtils()).isWeiboExist(blogId)){
            out.println(JsonOut.error(202, "weibo_not_exist"));
            return;
        }

        // 判断是否已赞
        if ((new MysqlUtils()).isLikeWeibo(email, blogId)){
            out.println(JsonOut.error(0, "weibo_liked"));
            return;
        }

        if (!(new MysqlUtils()).likeWeibo(email, blogId)){
            out.println(JsonOut.error(500, "sql_sth_wrong"));
            return;
        }

        out.println(JsonOut.error(0, "like_weibo_success"));
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        out.println(JsonOut.error(403, "forbidden"));
    }
}
